// pages/daily-practice/daily-practice.js
const app = getApp();

Page({
  data: {
    userInfo: {},
    questions: [],
    currentQuestionIndex: 0,
    selectedIndex: null,
    isCorrect: null,
    totalScore: 0,
    tempScore: 0,
    answeredToday: false,
    todayScore: 0,
    loadError: false // 新增加载状态
  },

  onLoad() {
    const localUserInfo = wx.getStorageSync('userInfo');
    if(!localUserInfo){
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.switchTab({ url: '/pages/mine/mine' });
      }, 2000);
      return;
    }
    this.getQuestionsFromDB().then(() => {
      this.initData();
    }).catch(err => {
      console.error('题目加载失败:', err);
      this.setData({ loadError: true });
      wx.showToast({
        title: '题目加载失败',
        icon: 'none',
        duration: 2000
      });
    });
  },

  // 从云数据库获取题目
  async getQuestionsFromDB() {
    try {
      const db = wx.cloud.database();
      const res = await db.collection('questions').get();
      
      if (!res.data || res.data.length === 0) {
        throw new Error('题库为空');
      }
      
      app.globalData.questions = res.data;
      return Promise.resolve();
    } catch (err) {
      console.error('数据库获取失败:', err);
      return Promise.reject(err);
    }
  },

  initData() {
    const totalScore = wx.getStorageSync('totalScore') || 0;
    const lastPracticeDate = wx.getStorageSync('lastPracticeDate');
    const today = new Date().toDateString();

    // 从全局获取题目
    const allQuestions = app.globalData.questions || [];
    
    if (allQuestions.length < 10) {
      this.setData({ loadError: true });
      wx.showToast({
        title: '题库数量不足',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 每日随机10题
    const shuffled = this.shuffleArray(allQuestions).slice(0, 10);

    if (lastPracticeDate !== today) {
      this.setData({
        questions: shuffled,
        currentQuestion: shuffled[0],
        currentQuestionIndex: 0,
        selectedIndex: null,
        isCorrect: null,
        tempScore: 0,
        answeredToday: false,
        loadError: false
      });
    } else {
      this.setData({
        answeredToday: true,
        questions: []
      });
    }

    this.setData({ totalScore });
  },

  shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  },

  selectOption(e) {
    if (this.data.isCorrect !== null) return;
    this.setData({ selectedIndex: e.currentTarget.dataset.index });
  },

  submitAnswer() {
    if (this.data.isCorrect !== null) return;
    const { questions, currentQuestionIndex, selectedIndex, tempScore } = this.data;
    const correctIndex = questions[currentQuestionIndex].answer;
    const isCorrect = selectedIndex === correctIndex;

    this.setData({
      isCorrect,
      tempScore: isCorrect ? tempScore + 1 : tempScore
    });

    wx.showToast({
      title: isCorrect ? '回答正确！' : `正确答案：${String.fromCharCode(65 + correctIndex)}`,
      icon: 'none',
      duration: 1500
    });

    setTimeout(() => {
      if (currentQuestionIndex < 9) {
        this.setData({
          currentQuestionIndex: currentQuestionIndex + 1,
          currentQuestion: questions[currentQuestionIndex + 1],
          selectedIndex: null,
          isCorrect: null
        });
      } else {
        this.completePractice();
      }
    }, 1500);
  },

  async completePractice() {
    const localUserInfo = wx.getStorageSync('userInfo');
    const phone = localUserInfo?.phone;

    if (!phone) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/login/login' });
      }, 2000);
      return;
    }

    const db = wx.cloud.database();
    const _ = db.command;
    const newTotal = this.data.totalScore + this.data.tempScore;
    const addPoints = this.data.tempScore * 10;

    try {
      const res = await db.collection('users').where({ phone }).get();
      if (res.data.length === 0) throw new Error('用户不存在');

      await db.collection('users').doc(res.data[0]._id).update({
        data: {
          points: _.inc(addPoints),
          totalScore: newTotal,
          lastPractice: db.serverDate()
        }
      });

      const userInfo = {
        ...localUserInfo,
        points: (localUserInfo.points || 0) + addPoints,
        totalScore: newTotal
      };
      
      wx.setStorageSync('userInfo', userInfo);
      wx.setStorageSync('lastPracticeDate', new Date().toDateString());

      this.setData({
        answeredToday: true,
        todayScore: this.data.tempScore,
        totalScore: newTotal,
        'userInfo.points': userInfo.points
      });

      wx.showToast({
        title: `获得${addPoints}积分`,
        icon: 'none',
        duration: 2000
      });

    } catch (err) {
      console.error('积分更新失败:', err);
      wx.showToast({
        title: '积分更新失败，请稍后重试',
        icon: 'none'
      });
    }
  }
});